const fs = require("fs");
const path = require("path");

global.name = "测试";

let blocksSetting = {};
function getBlockSchema(src) {
    try{
        const content = fs.readFileSync(src, "utf-8");
        const schemaRegExpStr = /{% schema %}([\s\S]*?){% endschema %}/g;
        const schemBody = content.match(schemaRegExpStr);
        if (schemBody) {
            return JSON.parse(schemBody[0].replace(/({% schema %})|({% endschema %})/g, ""));
        }
        return;    
    }catch(err){
        console.log('获取积木块配置失败',src);
    }
 
}
function writeFile(targetFile, content) {
    const dir = path.dirname(targetFile);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    fs.writeFileSync(targetFile, content);
}
function getDefaultBlock(src) {
    if (JSON.stringify(blocksSetting) == "{}") {
        const defaultDir = fs.readdirSync("./src/theme/default/sections");
        defaultDir.forEach(function (file) {
            const schemJson = getBlockSchema("./src/theme/default/sections" + "/" + file);
            if (schemJson) {
                blocksSetting[file.split(".")[0]] = schemJson;
            }
        });
    }

    const filenames = fs.readdirSync(src);
    filenames.forEach(function (file) {
        const schemJson = getBlockSchema(src + "/" + file);
        if (schemJson) {
            blocksSetting[file.split(".")[0]] = schemJson;
        }
    });
    return blocksSetting;
}

function themeList() {
    const themesFlie = fs.readdirSync("./src/theme");
    const blacklist = [".DS_Store", ".git", ".gitignore", ".vscode", "system","customtemp39391", "customtemp29831", "customtemp34484", "default", "test","component","nav-test"];
    return themesFlie.filter((item) => {
        return !blacklist.includes(item) && item.indexOf("customtemp") === -1;
    });
}
module.exports = {writeFile, getBlockSchema,getDefaultBlock, themeList };
